import datetime

from django.db import models
from django.db.models import Max

from users.models import UserInfo


class Retailer(models.Model):
    """商家"""
    FLAG = (
        (0, '待审'),
        (1, '通过'),
    )
    name = models.CharField(verbose_name='商家名称', max_length=64, blank=True, null=True)
    address = models.CharField(verbose_name='商家地址', max_length=128, blank=True, null=True)
    person = models.CharField(verbose_name='联系人', max_length=32, blank=True, null=True)
    telephone = models.CharField(verbose_name='联系电话', max_length=32, blank=True, null=True)
    openid = models.CharField(verbose_name='微信ID', max_length=32, blank=True, null=True)
    boss_name = models.CharField(verbose_name='姓名', max_length=64, blank=True, null=True)
    ratio = models.IntegerField(verbose_name='充值比例', blank=True, null=True)
    money = models.FloatField(verbose_name='充值金额', blank=True, null=True)
    score = models.IntegerField(verbose_name='积分', blank=True, null=True)
    gift_score = models.IntegerField(verbose_name='赠送积分', blank=True, null=True)
    flag = models.IntegerField(verbose_name='会员确认', blank=True, null=True, choices=FLAG)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '商家'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class RetailerImage(models.Model):
    """商家图片"""
    retailer = models.ForeignKey(Retailer, verbose_name='商品', related_name="images", on_delete=models.CASCADE, blank=True, null=True, db_constraint=False)
    name = models.CharField(verbose_name='图片名称', max_length=128, blank=True, null=True)
    image = models.ImageField(verbose_name='图片', upload_to='retailer/', blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '商家图片'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class Employee(models.Model):
    """员工授权"""
    openid = models.CharField(verbose_name='微信ID', max_length=32, blank=True, null=True)
    name = models.CharField(verbose_name='姓名', max_length=128, blank=True, null=True)
    role = models.ForeignKey(verbose_name='所属角色', to='WxRole', blank=True, null=True, db_constraint=False, on_delete=models.SET_NULL)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.openid

    class Meta:
        verbose_name = '员工授权'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class BonusPoint(models.Model):
    """赠送积分"""
    STATUS = (
        (0, '取消'),
        (1, '赠送'),
    )
    order_no = models.CharField(verbose_name='单号', max_length=16, blank=True, null=True)
    retailer = models.ForeignKey(Retailer, verbose_name='商家', blank=True, null=True, on_delete=models.DO_NOTHING, db_constraint=False)
    openid = models.CharField(verbose_name='商家微信ID', max_length=32, blank=True, null=True)
    name = models.CharField(verbose_name='姓名', max_length=128, blank=True, null=True)
    branch = models.CharField(verbose_name='分店', max_length=128, blank=True, null=True)
    customer_openid = models.CharField(verbose_name='客户微信ID', max_length=32, blank=True, null=True)
    customer_name = models.CharField(verbose_name='客户姓名', max_length=128, blank=True, null=True)
    score = models.IntegerField(verbose_name='赠送积分', blank=True, null=True)
    unused_score = models.IntegerField(verbose_name='待激活积分', blank=True, null=True)
    total_score = models.IntegerField(verbose_name='商家账户积分', blank=True, null=True)
    customer_total_score = models.IntegerField(verbose_name='客户账户积分', blank=True, null=True)
    order_key = models.CharField(verbose_name='单号key', max_length=64, blank=True, null=True)
    status = models.IntegerField(verbose_name='状态', blank=True, null=True, choices=STATUS)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.openid

    class Meta:
        verbose_name = '积分赠送明细'
        verbose_name_plural = verbose_name
        ordering = ["-id"]

    @classmethod
    def get_max_code(cls):
        year = datetime.datetime.now().strftime('%Y%m%d')
        max_code = cls.objects.filter(order_no__startswith=year).aggregate(max_code=Max("order_no"))
        max_value = max_code['max_code']
        if max_value is None:
            num = '0001'
            code = '{0}{1}'.format(year, num)
            return code
        else:
            num = str(int(max_value[-4:]) + 1).rjust(4, '0')
            code = '{0}{1}'.format(year, num)
            return code

    def save(self, *args, **kwargs):
        if not self.order_no:
            order_no = self.__class__.get_max_code()
            self.order_no = order_no
        return super().save(*args, **kwargs)


class PointConsumption(models.Model):
    """客户积分消费"""
    openid = models.CharField(verbose_name='客户微信ID', max_length=32, blank=True, null=True)
    name = models.CharField(verbose_name='客户姓名', max_length=128, blank=True, null=True)
    employee_openid = models.CharField(verbose_name='商家微信ID', max_length=32, blank=True, null=True)
    employee_name = models.CharField(verbose_name='员工姓名', max_length=128, blank=True, null=True)
    score = models.IntegerField(verbose_name='消费积分', blank=True, null=True)
    total_score = models.IntegerField(verbose_name='剩余积分', blank=True, null=True)
    consume_key = models.CharField(verbose_name='消费Key', max_length=64, blank=True, null=True)
    update_time = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    add_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '客户积分消费'
        verbose_name_plural = verbose_name
        ordering = ["-id"]


class WxPermission(models.Model):
    """
    权限表
    """
    FLAG = (
        (0, '商家可见'),
        (1, '员工可见'),
        (2, '管理员可见'),
    )
    name = models.CharField(verbose_name='权限名称', max_length=64)
    path = models.CharField(verbose_name='权限路径', max_length=256)
    comment = models.CharField(verbose_name='权限简介', max_length=256, blank=True, null=True)
    icon = models.CharField(verbose_name='图标', max_length=64, blank=True, null=True)
    flag = models.IntegerField(verbose_name='类型', choices=FLAG, blank=True, null=True)
    update_at = models.DateTimeField(verbose_name='修改时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '权限管理'
        verbose_name_plural = verbose_name
        ordering = ['id']


class WxRole(models.Model):
    """
    角色
    """
    name = models.CharField(verbose_name='角色名称', max_length=32)
    comment = models.CharField(verbose_name='角色说明', max_length=128, blank=True, null=True)
    retailer = models.ForeignKey(Retailer, verbose_name='商家', on_delete=models.CASCADE, db_constraint=False, blank=True, null=True)
    permissions = models.ManyToManyField(verbose_name='角色权限', to='WxPermission', blank=True, db_constraint=False)
    update_at = models.DateTimeField(verbose_name='创建时间', auto_now=True)
    create_at = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '角色管理'
        verbose_name_plural = verbose_name
        ordering = ['-create_at']
